<template>
  <div class="app-content">
    <el-form class="crud-search-form" inline>
      <el-form-item label="主机地址">
        <el-input placeholder="请输入主机地址" v-model.trim="queryParams.ip" clearable></el-input>
      </el-form-item>
      <el-form-item label="登录地址">
        <el-input placeholder="请输入登录地址" v-model.trim="queryParams.address" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户账号">
        <el-input placeholder="请输入用户账号" v-model.trim="queryParams.username" clearable></el-input>
      </el-form-item>
      <el-form-item label="登录状态">
        <el-select v-model="queryParams.status" placeholder="请选择登录状态" clearable style="width: 200px">
          <el-option :value="0" label="失败" />
          <el-option :value="1" label="成功" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <ep-button plain svgIcon="Refresh" type="danger" @click="resetQuery">重置</ep-button>
        <ep-button plain svgIcon="Search" type="primary" @click="handleQuery">查询</ep-button>
      </el-form-item>
    </el-form>

    <div class="mb-16px flex items-center">
      <ep-button svg-icon="Close" type="danger" plain @click="clearLogininfo" :disabled="isEmpty">清空</ep-button>
      <ep-button svg-icon="Download" type="success" plain @click="exportExcel" :disabled="isEmpty">导出</ep-button>
    </div>

    <ep-table :data="logininfoList" :columns>
      <template #status="{ row }">
        <el-tag type="primary" v-if="row.status === 1">成功</el-tag>
        <el-tag type="danger" v-else>失败</el-tag>
      </template>
      <template #action="{ row }">
        <el-link type="danger" @click="handleDelete(row.id)">删除</el-link>
      </template>
    </ep-table>

    <EpPagination :total v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup lang="ts">
import { extractFilename, linkDownload, TipModal } from '@/utils'
import { LogininfoRequest } from '@/api/monitor/logininfo.request'

const loading = ref<boolean>(false)
const total = ref<number>(0) // 总条数
const logininfoList = ref<LogininfoType.Entity[]>([]) // 表格数据
const queryParams = ref({ pageNo: 1, pageSize: 10 } as TableQueryParams<LogininfoType.Entity>)
const isEmpty = computed(() => logininfoList.value.length === 0)
const columns: TableColumnProp<LogininfoType.Entity>[] = [
  { align: 'center', prop: 'id', label: '访问编号', minWidth: '120', showOverflowTooltip: true },
  { align: 'center', prop: 'username', label: '用户账号', minWidth: '120' },
  { align: 'center', prop: 'ip', label: '主机地址', minWidth: '150' },
  { align: 'center', prop: 'address', label: '登录地址', minWidth: '150' },
  { align: 'center', prop: 'browser', label: '浏览器', minWidth: '170' },
  { align: 'center', prop: 'os', label: '操作系统', minWidth: '180' },
  { align: 'center', slot: 'status', label: '登录状态', minWidth: '90' },
  { align: 'center', prop: 'message', label: '操作信息', minWidth: '200', showOverflowTooltip: true },
  { align: 'center', prop: 'loginTime', label: '登录时间', minWidth: '170' },
  { align: 'center', slot: 'action', label: '操作', minWidth: '100', fixed: 'right' },
]

/** 查询登录日志列表 */
async function getList() {
  try {
    loading.value = true
    const data = await LogininfoRequest.findList(queryParams.value)
    total.value = data.total
    logininfoList.value = data.records
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}

function handleQuery() {
  queryParams.value.pageNo = 1
  getList()
}

function resetQuery() {
  const keys = Object.keys(queryParams.value).filter((key) => key !== 'pageSize')
  keys.forEach((key) => Reflect.deleteProperty(queryParams.value, key))
  handleQuery()
}

async function handleDelete(ids: string | string[]) {
  const { cancel } = await TipModal.confirm(`确定要删除选中的数据吗？`)
  if (cancel) return TipModal.msg(`操作取消`)
  const deleteIds = Array.isArray(ids) ? ids.join(',') : ids
  await LogininfoRequest.delete({ ids: deleteIds })
  if (logininfoList.value.length <= 1) queryParams.value.pageNo = queryParams.value.pageNo! > 1 ? queryParams.value.pageNo! - 1 : 1
  getList()
  TipModal.msgSuccess(`删除成功`)
}

/** 清空登录日志 */
async function clearLogininfo() {
  const { cancel } = await TipModal.confirm(`确定要清空所有的登录日志吗？`)
  if (cancel) return TipModal.msg(`操作取消`)
  const msg = await LogininfoRequest.clear()
  getList()
  TipModal.msgSuccess(msg || `登录日志清空成功`)
}

/** 导出登录日志 */
async function exportExcel() {
  const response = await LogininfoRequest.exportExcel()
  const fileName = extractFilename(response) ?? `登录日志.xlsx`
  const buffer = response.data
  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  linkDownload(blob, fileName)
}

getList()
</script>

<style lang="scss" scoped></style>
